package cn.buddha.jec.flowable.handler;

import cn.buddha.jec.db.service.IFlowableInfoService;
import cn.buddha.jec.flowable.constant.FlowableStatus;
import cn.buddha.jec.model.TongBaseResponse;
import cn.buddha.jec.model.TongContext;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName PostHandler
 * @Author 友野浩二
 * @Date 2020/4/1 21:44
 * @Description 业务逻辑处理之后的公共处理(框架层)
 * @Version 1.0
 */
@Component
@Slf4j
public class PostHandler {

    /**
     * 是否开启"登记flowableInfo"开关,默认false
     */
    @Value("${flowableInfo.enable:false}")
    private Boolean enableFlowableInfo;

    /**
     * 服务流程信息 服务类
     */
    @Resource
    private IFlowableInfoService flowableInfoServiceImpl;

    public void handler(final TongBaseResponse output) {
        log.info("<===== postHandler starting =====>");
        // 创建自动start的计时器(记录服务流程框架后置通知的耗时时间)
        Stopwatch stopwatch = Stopwatch.createStarted();

        if (enableFlowableInfo) {
            try {
                // 更新服务流程信息
                this.flowableInfoServiceImpl.updateFlowableInfo(output, FlowableStatus.STATUS_SUCCESS);
            } catch (Exception e) {
                // 这里只打印异常，不抛出异常。
                log.error("业务逻辑处理之后的正常公共处理异常", e);
            }
        }

        if (log.isInfoEnabled()) {
            log.info("服务流程框架后置[{}]耗时[{}ms]", TongContext.getInstance().getReqUrl(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
        log.info("<===== postHandler end =====>");
    }

}
